import { defineStore } from "pinia";
import { store } from '../index'
interface AdminStore {
    menus: MenusType[];
}

export const useAdminStore = defineStore('admin', {
    state():AdminStore {
        return {
            menus: []
        }
    },
    actions: {
        updateMenus(menus: MenusType[]) {
            this.menus = menus
        }
    },
    getters: {
        genNewMenus(state) {
            // extends约束  in：映射(循环) 类似于for(let key in obj)；
            // type Record<K extends string | number | symbol, T> = { [P in K]: T; }
            const newMenus: Recordable<MenusType> = {};
            state.menus.forEach(item => {
                if (item.parentId === 0) {
                    // newMenus.push(item)
                    newMenus[item.id] = {
                        ...item,
                        children:newMenus[item.parentId]?.children??[],
                    };
                } else {
                    // 子菜单对应的父id
                    newMenus[item.parentId] ??= {} as MenusType;
                    newMenus[item.parentId].children ??= [];
                    newMenus[item.parentId].children.push(item);
                }
            })
            return newMenus;
        }
    }
})

// 脱离setup生命周期后store不能再使用，需要将store导出供外部使用
export const useAdminStoreWithOut = () => useAdminStore(store);